import filter from './filterApiUrl'
const request = (options) => {
  const isLogin = options?.data?.isLogin || false
  const app = getApp()
  const BASE_URL = app.globalData.BASE_URL
  const Token = wx.getStorageSync('Token') || '';
  const str = options.url.indexOf('?') != -1 ? options.url.split('?').shift() : options.url
  const boo = filter.indexOf(str) == -1
  const header = {
    // Authorization: boo ? (Token ? `wx${Token}` : '') : '',
    Authorization: Token ? `wx${Token}` : '',
    'Content-Type': 'application/json;charset=UTF-8',
    ...options.header,
  }
  const request = {
    url: BASE_URL + options.url,
    method: options.method || 'GET',
    data: options.data || null,
    header,
    dataType: 'json',
    complete: () => options.complete instanceof Function ? options.complete() : null
  };
  !request.data ? delete request.data : null;
  !request.complete ? delete request.complete : null;
  return new Promise((resolve, reject) => {
    wx.request({
      ...request,
      success: (response) => {
        const res = response.data;
        const shareId = app.globalData.shareId || ''
        if (res.code == 401 && !isLogin) return (reject(res), wx.navigateTo({ url: `/pages/login/login?shareId=${shareId}` }))
        if (res.code != 200 && !isLogin) return (reject(res), setTimeout(() => showToast(res.msg), 500))
        resolve(res)
      },
      fail: (err) => (showToast('系统错误!'), reject(err))
    })
  })
};

const get = (url, options) => {
  let method = 'GET', data = null, header = {}, complete = null;
  if (options instanceof Object) {
    let optionsData = JSON.parse(JSON.stringify(options));
    delete optionsData.header
    delete optionsData.complete
    data = optionsData;
    header = options.header || {}
    complete = options.complete || null
  }
  return request({ url, method, header, data, complete })
};

const post = (url, options) => {
  let method = 'POST', data = null, header = {}, complete = null;
  if (options instanceof Object) {
    let optionsData = JSON.parse(JSON.stringify(options));
    delete optionsData.header
    delete optionsData.complete
    data = optionsData;
    header = options.header || {}
    complete = options.complete || null
  }
  return request({ url, method, header, data, complete })
};

const showToast = (title = '', icon = 'none', duration = 2000) => new Promise((resolve, reject) => wx.showToast({ title, duration, icon, success: () => setTimeout(() => resolve(), duration), fail: () => reject() }));
const showSuccess = (title = '操作成功', icon = 'success', duration = 2000, mask = true) => new Promise((resolve, reject) => wx.showToast({ title, duration, icon, mask, success: () => setTimeout(() => resolve(), duration), fail: () => reject() }));
const showLoading = (title = '加载中...', mask = true) => wx.showLoading({ title, mask });
const showModal = (text, showCancel = true) => new Promise((resolve, reject) => wx.showModal({ title: '提示', content: text, showCancel, success: (res) => res.confirm ? resolve(true) : resolve(false) }))
const uploadFile = (options, url = '/wx/appletFeedback/uploadimg') => new Promise((resolve, reject) => {
  console.log('uploadFile', options)
  const filePath = options.filePath
  const BASE_URL = getApp().globalData.BASE_URL
  const token = wx.getStorageSync('Token')
  const formData = options || { [options?.name || 'file']: filePath }
  wx.uploadFile({
    url: `${BASE_URL}${url}`, //post请求的地址
    filePath,
    name: options?.name || 'file',
    formData,
    header: { Authorization: token ? `wx${token}` : '', 'Content-Type': 'application/json;charset=UTF-8', },
    success: (res) => {
      if (res.statusCode != 200) return (showToast('系统错误, 请联系管理员'), reject())
      const result = JSON.parse(res.data)
      if (result.code != 200) return (showToast(res.msg), reject())
      resolve(result)
    },
    fail: (err) => reject(err)
  })
});

/**
 * 文件下载
 */
const downloadFile = (url) => {
  wx.downloadFile({
    url: (url.indexOf('http') == -1 ? BASE_URL : '') + url,
    header: {
      Authorization: 'wx' + wx.getStorageSync('token')
    },
    success: function (res) {
      var filePath = res.tempFilePath;
      console.log(filePath);
      wx.openDocument({
        filePath: filePath,
        success: function (res) {
          console.log('打开文档成功')
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function (res) {
          console.log(res);
        }
      })
    },
    fail: function (res) {
      console.log('文件下载失败');
    },
  })
}


const getLoginCode = () => new Promise((resolve, reject) => wx.login({ success: (res) => resolve(res), fail: (err) => reject(err) }));

const getUserPro = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用于完善用户资料',
      success: (res) => resolve(res),
      fail: (err) => resolve(err)
    })
  })
}
const getUserInfo = async (param) => {
  const res = await get('/wx/user/info', param || null)
  if (!res.data || !res.data.user || !res.data.user.roles) return null
  res?.data?.user?.roles ? res.data.user.roles = JSON.parse(res.data.user.roles) : null
  wx.setStorageSync('userInfo', res.data.user)
  res.data.user.permissions = res.data.permissions
  res.data.user.role = res.data.roles
  return res.data.user
}

export default {
  get,
  post,
  getLoginCode,
  getUserPro,
  uploadFile,
  downloadFile,
  showSuccess,
  showToast,
  showModal,
  showLoading,
  getUserInfo
};